package com.fenqing.leetcode.code.interview;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fenqing.annotations.Execute;
import com.fenqing.core.Topic;

import java.util.stream.Collectors;

/**
 * @author fenqing
 */
public class Topic0108 extends Topic {

    /**
     * 构造器
     *
     * @param input     输入
     */
    public Topic0108(String input) {
        super(input);
    }

    @Execute
    public void setZeroes(int[][] matrix) {
        boolean rowFlag = false, colFlag = false;
        int row = matrix.length, col = matrix[0].length;
        for (int[] ints : matrix) {
            if (ints[0] == 0) {
                rowFlag = true;
                break;
            }
        }
        for (int i = 0; i < col; i++) {
            if (matrix[0][i] == 0) {
                colFlag = true;
                break;
            }
        }
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        if (rowFlag) {
            for (int i = 0; i < row; i++) {
                matrix[i][0] = 0;
            }
        }
        if (colFlag) {
            for (int j = 0; j < col; j++) {
                matrix[0][j] = 0;
            }
        }
    }

    public static void main(String[] args) {
        String input = "[[0,1,2,0],[3,4,5,2],[1,3,1,5]]";
        Topic topic = new Topic0108(input);
        String output = topic.run();
        System.out.println("input: \n" + print(input));
        System.out.println("output: \n" + print(output));
    }

    public static String print(String matrix) {
        JSONArray objects = JSONUtil.parseArray(matrix);
        return "[\n" +
                objects.stream().map(JSONUtil::toJsonStr).collect(Collectors.joining(",\n")) +
                "\n]";
    }
}
